<template>

  <div class="app-container">
    <el-row :gutter="20">
      <!--分组数据-->
      <el-col v-if="isShow" :span="4" :xs="24">
        <div class="head-container">
          <el-input
              v-model="name"
              type="text"
              :placeholder="$t('equipment.channelNameInput')"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
              @input="change(name)"
          />
        </div>
        <div class="head-container tree leftBox">
          <el-tree
              ref="tree"
              :data="treeData"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :highlight-current="true"
              default-expand-all
              @node-click="handleNodeClick"
          >
            <div slot-scope="{ node, data }" class="el-tree-node__label custom-tree-node custom-tree-item"
                 style="position: relative;"
            >
              <span class="name">{{ data.name }}</span>
              <svg-icon style="padding-left: 3px;font-size: 18px" v-hasPerm="['group_edit']" icon-class="edit"
                        @click="handleEdit(data)"
              />
              <svg-icon style="padding-left: 3px;font-size: 18px" v-hasPerm="['group_del']" icon-class="delete"
                        @click="handleDle(data)"
              />
            </div>
          </el-tree>
        </div>
      </el-col>
      <el-col v-if="isShow" :span="20" :xs="24">
        <full-calendar ref="fullCalendar" style="height: 100%" :options="calendarOptions"/>
      </el-col>
      <el-col v-show="!isShow" :span="24" :xs="24">
        <scheduling ref="scheduling" @open="open" @getTreeList="getTreeList"/>
      </el-col>
      <el-col v-show="false" :span="24" :xs="24">
        <releasePlan ref="releasePlan"/>
      </el-col>
    </el-row>
    <div class="corner-buttons">
      <div class="hover-buttons">
        <el-tooltip class="item" effect="dark" :content="$t('elButton.release')" placement="left">
          <el-button circle icon="el-icon-s-promotion" style="font-size: 20px"
                     @click="releasePlanHandleAdd"
          >
          </el-button>
        </el-tooltip>
        <br>
        <el-tooltip class="item" effect="dark" :content="$t('elButton.add')" placement="left">
          <el-button circle icon="el-icon-plus" style="font-size: 20px" type="primary" @click="handleAdd"
          ></el-button>
        </el-tooltip>
      </div>
      <div style="padding-top: 15px">
        <el-button circle size="mini" type="primary" icon="el-icon-edit" style="font-size: 30px"
        ></el-button>
      </div>
    </div>

  </div>
</template>

<script>
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import listPlugin from '@fullcalendar/list'
import resourceTimeGridPlugin from '@fullcalendar/resource-timegrid'
import resourceTimelinePlugin from '@fullcalendar/resource-timeline'
import interactionPlugin from '@fullcalendar/interaction'
import { listScheduling } from '@/api/ips/scheduling'
import scheduling from './new_scheduling'
import releasePlan from '../releasePlan/index'
import { delScheduling } from '@/api/ips/scheduling'

export default {
  components: { FullCalendar, scheduling, releasePlan },
  data() {
    return {
      isShow: true,
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        id: 'id'
      },
      calendarOptions: {
        schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
        height: 700,
        plugins: [resourceTimeGridPlugin, dayGridPlugin, listPlugin, resourceTimelinePlugin, interactionPlugin],
        initialView: 'dayGridMonth', // 设置默认显示月，可选周、日
        headerToolbar: {
          left: 'prevYear,prev,next,nextYear,today',
          center: 'title',
          right: 'month,week,day,new_list'
        },
        buttonText: { // 设置按钮
          today: '今天',
          month: '月',
          week: '周',
          day: '日'
        },
        slotLabelFormat: {
          hour: '2-digit',
          minute: '2-digit',
          meridiem: false,
          hour12: false // 设置时间为24小时
        },

        allDaySlot: false,
        eventClick: this.handleEventClick,
        displayEventEnd: true, // 所有视图显示结束时间
        // 设置日程
        events: [],
        eventColor: '#0FE7CE', // 修改日程背景色
        locale: 'zh-cn', // 设置语言
        weekNumberCalculation: 'ISO', // 周数
        customButtons: {
          prev: {
            text: 'PREV',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.prev()
              // this.getList()
            }
          },
          next: { // this overrides the next button
            text: 'PREV',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.next()
              // this.getList()
            }
          },
          today: {
            text: '今天',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.today()
              // this.getList()
            }
          },
          prevYear: {
            text: 'prevYear',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.prevYear()
              // this.getList()
            }
          },
          nextYear: {
            text: 'nextYear',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.nextYear()
              // this.getList()
            }
          },
          new_list: {
            text: '列表',
            click: () => {
              this.isShow = false
            }
          },
          month: {
            text: '月',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.changeView('dayGridMonth')
              // this.getList()
            }
          },
          week: {
            text: '周',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.changeView('timeGridWeek')
              // this.getList()
            }
          },
          day: {
            text: '日',
            click: () => {
              const calendarApi = this.$refs.fullCalendar.getApi()
              calendarApi.changeView('timeGridDay')
              // this.getList()
            }
          }
        }
      }
    }
  },
  mounted() {
    // this.getList()
    this.getTreeList()
    // console.log(this.getIsContain('0,1,2,3,4,5,6', '2021-04-02'))
  },
  methods: {
    async handleAdd() {
      await this.$nextTick()
      this.$refs.scheduling.handleAdd()
    },
    async handleEdit(data) {
      await this.$refs.scheduling.handleEdit(data)
    },
    async handleDle(data) {
      await this.$refs.scheduling.handleDel(data)
    },
    releasePlanHandleAdd() {
      this.$refs.releasePlan.handleAdd()
    },
    handleEventClick(data) {
      /** 删除按钮操作 */
      const ids = data.event._def.publicId
      this.$confirm(this.$t('equipment.deleteChanel') + ids + this.$t('equipment.deleteEquipment2'), this.$t('warning'), {
        confirmButtonText: this.$t('submitText'),
        cancelButtonText: this.$t('cancelText'),
        type: 'warning'
      }).then(function() {
        return delScheduling(ids)
      }).then(() => {
        this.getTreeList()
        this.msgSuccess(this.$t('deleteSuccess'))
      }).catch(function() {

      })
    },

    handleNodeClick(row) {
      const calendarApi = this.$refs.fullCalendar.getApi()
      this.calendarOptions.events = []
      if (calendarApi.view.type === 'dayGridMonth') { // 月份查询
        this.dayGridMonthDeal(calendarApi, row)
      } else if (calendarApi.view.type === 'timeGridWeek') { // 周查询
        this.timeGridWeekDeal(calendarApi, row)
      } else if (calendarApi.view.type === 'timeGridDay') { // 日查询
        this.timeGridDayDeal(calendarApi, row)
      }
    },
    change(e) {
      this.$forceUpdate()
      this.getTreeList(e)
    },
    // 获取树列表
    getTreeList(e) {
      const calendarApi = this.$refs.fullCalendar.getApi()
      listScheduling({ current: 1, size: 999, name: e }).then(response => {
        this.treeData = response.data
        this.calendarOptions.events = []
        if (this.treeData.length > 0) {
          this.dayGridMonthDeal(calendarApi, this.treeData[0])
        }
      })
    },

    getList() {
      const calendarApi = this.$refs.fullCalendar.getApi()
      // dayGridMonth, timeGridWeek, timeGridDay
      // if (calendarApi.view.type === 'dayGridMonth') { // 月份查询
      //   const title = calendarApi.view.title.replace('年', '').replace('月', '')
      //   let newTitle = title
      //   if (title.length === 5) {
      //     newTitle = title.substring(0, 4) + '0' + title.substring(4, 5)
      //   }
      //   searchForm.month = newTitle
      // } else if (calendarApi.view.type === 'timeGridWeek') {

      // } else if (calendarApi.view.type === 'timeGridDay') {

      // }
      listScheduling().then(response => {
        if (response.data.length > 0) {
          this.calendarOptions.events = []
          response.data.forEach(element => {
            if (calendarApi.view.type === 'dayGridMonth') { // 月份查询
              this.dayGridMonthDeal(calendarApi, element)
            } else if (calendarApi.view.type === 'timeGridWeek') { // 周查询
              this.timeGridWeekDeal(calendarApi, element)
            } else if (calendarApi.view.type === 'timeGridDay') { // 日查询
              this.timeGridDayDeal(calendarApi, element)
            }
          })
        }
      })
    },

    // dayGridMonth 月事件处理
    dayGridMonthDeal(calendarApi, element) {
      const year = calendarApi.view.title.split('年')[0]
      const month = calendarApi.view.title.split('年')[1]
      const month1 = month.replace('月', '')
      const newMonth = month1 >= 10 ? month1 : '0' + month1
      const tempDate = this.getStartAndEndDate(year.replace('年', ''), newMonth, element)
      if (tempDate.length > 0) {
        this.calendarOptionsAdd(tempDate, element)
      }
    },
    calendarOptionsAdd(tempDate, form) {
      if (tempDate.length > 0) {
        tempDate.forEach(element => {
          if (form.startTime === '00:00:00' && form.stopTime === '23:59:59') {
            this.calendarOptions.events.push({
              id: form.id,
              title: form.name,
              start: element[0] + ' ' + form.startTime,
              end: element[element.length - 1] + ' ' + form.stopTime,
              textColor: 'black'
            })
          } else {
            element.forEach(element1 => {
              this.calendarOptions.events.push({
                id: form.id,
                title: form.name,
                start: element1 + ' ' + form.startTime,
                end: element1 + ' ' + form.stopTime,
                textColor: 'black'
              })
            })
          }
        })
      }
    },
    // timeGridWeek 周事件处理
    timeGridWeekDeal(calendarApi, element) {
      const startDate = this.dateFormat(calendarApi.view.currentStart)
      let tempList = []
      const tempAll = []
      for (let i = 0; i < 7; i++) {
        if (this.compareDate(this.getTime(i, startDate), element.startDate, element.stopDate) &&
            this.getIsContain(element.playWeeks, this.getTime(i, startDate))) {
          tempList.push(this.getTime(i, startDate))
        } else {
          if (tempList.length > 0) {
            tempAll.push(tempList)
          }
          tempList = []
        }
      }
      if (tempAll.length === 0 && tempList.length > 0) {
        tempAll.push(tempList)
      }
      if (tempAll.length > 0) {
        this.calendarOptionsAdd(tempAll, element)
      }
    },
    getTime(num, someday) {
      return this.dateFormat(new Date(someday).getTime() + 60 * 60 * 24 * 1000 * num)
    },
    // timeGridDay 日事件处理
    timeGridDayDeal(calendarApi, element) {
      const date = calendarApi.view.title.replace('年', '-').replace('月', '-').replace('日', '')
      if (this.compareDate(date, element.startDate, element.stopDate)) {
        this.calendarOptions.events.push({
          id: element.id,
          title: element.name,
          start: this.dateFormat(date) + ' ' + element.startTime,
          end: this.dateFormat(date) + ' ' + element.stopTime,
          textColor: 'black'
        })
      }
    },
    // dayGridMonth 获取满足时间区间
    getStartAndEndDate(year, month, element) {
      const startDate = element.startDate
      const endDate = element.stopDate
      const tempAll = []
      let temp = []
      month = parseInt(month, 10)
      const lastDayOfMonth = new Date(year, month, 0).getDate()
      for (let i = 1; i <= lastDayOfMonth; i++) {
        let item = ''
        if (i < 10) {
          item = year + '-' + (month > 10 ? month : '0' + month) + '-' + '0' + i
        } else {
          item = year + '-' + (month > 10 ? month : '0' + month) + '-' + i
        }
        if (this.compareDate(item, startDate, endDate) && this.getIsContain(element.playWeeks, item)) {
          temp.push(item)
        } else {
          if (temp.length > 0) {
            tempAll.push(temp)
          }
          temp = []
        }
      }
      if (tempAll.length === 0 && temp.length > 0) {
        tempAll.push(temp)
      }
      return tempAll
    },
    // 是否满足周几
    getIsContain(playWeeks, date) {
      const newDate = new Date(date)
      return playWeeks.indexOf(newDate.getDay()) !== -1
    },

    // 时间格式转换
    dateFormat(date1) {
      var date = new Date(date1)
      var year = date.getFullYear() // 获取当前年份
      var mon = date.getMonth() + 1 // 获取当前月份
      var da = date.getDate() // 获取当前日
      return year + '-' + (mon > 9 ? mon : '0' + mon) + '-' + (da > 9 ? da : '0' + da)
    },

    // 比较时间是否在开始结束区间内
    compareDate(date1, date2, date3) {
      var oDate = new Date(date1)
      var startData = new Date(date2)
      var endData = new Date(date3)
      if (oDate.getTime() >= startData.getTime() && oDate.getTime() <= endData.getTime()) {
        return true // 第一个大
      } else {
        return false // 第二个大
      }
    },

    // 子组件返回父组件
    open(data) {
      this.isShow = true
      this.calendarOptions.initialView = data
    },

    // 点击当天
    dayClick: function(date, jsEvent, view) {
      console.log('')
    }

  }
}
</script>
<style scoped lang="scss">
.leftBox {
  height: 700px;
  overflow: auto;
}

.corner-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: fixed;
  right: 2%;
  bottom: 20%;
  z-index: 10000;
  .hover-buttons {
    display: none;
    flex-direction: column;
  }

}

.corner-buttons:hover .hover-buttons {
  display: flex;
  flex-direction: column;

}
</style>
